package info.androidhive.pratap;

import info.androidhive.pratap.services.DownloadService;
import info.androidhive.volleyexamples.R;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class DownLoadServiceActivity extends Activity {

	private TextView textView;
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				String string = bundle.getString(DownloadService.FILEPATH);
				int resultCode = bundle.getInt(DownloadService.RESULT);
				if (resultCode == RESULT_OK) {
					Toast.makeText(DownLoadServiceActivity.this,
							"Download complete. Download URI: " + string,
							Toast.LENGTH_LONG).show();
					textView.setText("Download done");
				} else {
					Toast.makeText(DownLoadServiceActivity.this,
							"Download failed", Toast.LENGTH_LONG).show();
					textView.setText("Download failed");
				}
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.downlaodservice_activity);
		textView = (TextView) findViewById(R.id.status);

	}

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(receiver, new IntentFilter(
				DownloadService.NOTIFICATION));
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiver);
	}

	public void onClick(View view) {

		Intent intent = new Intent(this, DownloadService.class);
		// add infos for the service which file to download and where to store
		intent.putExtra(DownloadService.FILENAME, "AndroidAppDevDunmmies.pdf");
		intent.putExtra(DownloadService.URL,
				"https://dl.dropboxusercontent.com/u/83669745/jsonurls/Android%20Application%20Development%20for%20Dummies.pdf");
		startService(intent);
		textView.setText("Service started");
	}
}